﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.SessionState;
using QuickORM.BLL;

namespace QuickORM.Common
{
    public class Util
    {
        #region "返回字符串在字符串中出现的次数"

        /// <summary>
        ///     返回字符串在字符串中出现的次数
        /// </summary>
        /// <param name="Char">要检测出现的字符</param>
        /// <param name="String">要检测的字符串</param>
        /// <returns>出现次数</returns>
        public static int GetCharInStringCount(string Char, string String)
        {
            var str = String.Replace(Char, "");
            return (String.Length - str.Length)/Char.Length;
        }

        #endregion

        #region "获得物理路径"

        /// <summary>
        ///     获得物理路径
        /// </summary>
        /// <param name="a">路径</param>
        /// <returns>物理路径</returns>
        public static string GetFullPath(string a)
        {
            var AppDir = AppDomain.CurrentDomain.BaseDirectory;
            if (a.IndexOf(":") < 0)
            {
                var str = a.Replace("..\\", "");
                if (str != a)
                {
                    var Num = (a.Length - str.Length)/("..\\").Length + 1;
                    for (var i = 0; i < Num; i++)
                    {
                        AppDir = AppDir.Substring(0, AppDir.LastIndexOf("\\"));
                    }
                    str = "\\" + str;
                }
                a = AppDir + str;
            }
            return a;
        }

        #endregion

        #region 截取字符串

        /// <summary>
        ///     截取字符串
        /// </summary>
        /// <param name="str_value"></param>
        /// <param name="str_len"></param>
        /// <returns></returns>
        public static string leftx(string str_value, int str_len)
        {
            var p_num = 0;
            int i;
            var New_Str_value = "";

            if (str_value == "")
            {
                New_Str_value = "";
            }
            else
            {
                var Len_Num = str_value.Length;
                for (i = 0; i <= Len_Num - 1; i++)
                {
                    if (i > Len_Num) break;
                    var c = Convert.ToChar(str_value.Substring(i, 1));
                    if ((c > 255) || (c < 0))
                        p_num = p_num + 2;
                    else
                        p_num = p_num + 1;


                    if (p_num >= str_len)
                    {
                        New_Str_value = str_value.Substring(0, i + 1);
                        break;
                    }
                    New_Str_value = str_value;
                }
            }
            return New_Str_value;
        }

        #endregion

        #region 检测用户提交页面

        /// <summary>
        ///     检测用户提交页面
        /// </summary>
        /// <param name="rq"></param>
        public static void Check_Post_Url(HttpContext rq)
        {
            var WebHost = "";
            if (rq.Request.ServerVariables["SERVER_NAME"] != null)
            {
                WebHost = rq.Request.ServerVariables["SERVER_NAME"];
            }

            var From_Url = "";
            if (rq.Request.UrlReferrer != null)
            {
                From_Url = rq.Request.UrlReferrer.ToString();
            }

            if (From_Url == "" || WebHost == "")
            {
                rq.Response.Write("禁止外部提交数据!");
                rq.Response.End();
            }
            else
            {
                WebHost = "HTTP://" + WebHost.ToUpper();
                From_Url = From_Url.ToUpper();
                var a = From_Url.IndexOf(WebHost);
                if (From_Url.IndexOf(WebHost) < 0)
                {
                    rq.Response.Write("禁止外部提交数据!");
                    rq.Response.End();
                }
            }
        }

        #endregion

        #region 随机颜色数据

        /// <summary>
        ///     随机颜色数据
        /// </summary>
        /// <returns></returns>
        public static string getStrColor()
        {
            var length = 6;
            var random = new byte[length/2];
            var rng = new RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(random);

            var sb = new StringBuilder(length);
            int i;
            for (i = 0; i < random.Length; i++)
            {
                sb.Append(string.Format("{0:X2}", random[i]));
            }
            return sb.ToString();
        }

        #endregion

        #region "隐藏IP地址最后一位用*号代替"

        /// <summary>
        ///     隐藏IP地址最后一位用*号代替
        /// </summary>
        /// <param name="Ipaddress">IP地址:192.168.34.23</param>
        /// <returns></returns>
        public static string HidenLastIp(string Ipaddress)
        {
            return Ipaddress.Substring(0, Ipaddress.LastIndexOf(".")) + ".*";
        }

        #endregion

        #region "防刷新检测"

        /// <summary>
        ///     防刷新检测
        /// </summary>
        /// <param name="Second">访问间隔秒</param>
        /// <param name="UserSession"></param>
        public static bool CheckRefurbish(int Second, HttpSessionState UserSession)
        {
            var i = true;
            if (UserSession["RefTime"] != null)
            {
                var d1 = Convert.ToDateTime(UserSession["RefTime"]);
                var d2 = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
                var d3 = d2.Subtract(d1);
                if (d3.Seconds < Second)
                {
                    i = false;
                }
                else
                {
                    UserSession["RefTime"] = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
                }
            }
            else
            {
                UserSession["RefTime"] = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
            }

            return i;
        }

        #endregion

        #region "判断是否是Decimal类型"

        /// <summary>
        ///     判断是否是Decimal类型
        /// </summary>
        /// <param name="TBstr0">判断数据字符</param>
        /// <returns>true是false否</returns>
        public static bool IsDecimal(string TBstr0)
        {
            var IsBool = false;
            var Intstr0 = "1234567890";
            string IntSign0, StrInt, StrDecimal;
            int IntIndex0, IntSubstr, IndexInt;
            var decimalbool = 0;
            var db = 0;
            bool Bf, Bl;
            if (TBstr0.Length > 2)
            {
                IntIndex0 = TBstr0.IndexOf(".");
                if (IntIndex0 != -1)
                {
                    var StrArr = ".";
                    var CharArr = StrArr.ToCharArray();
                    var NumArr = TBstr0.Split(CharArr);
                    IndexInt = NumArr.GetUpperBound(0);
                    if (IndexInt > 1)
                    {
                        decimalbool = 1;
                    }
                    else
                    {
                        StrInt = NumArr[0];
                        StrDecimal = NumArr[1];
                        //--- 整数部分－－－－－
                        if (StrInt.Length > 0)
                        {
                            if (StrInt.Length == 1)
                            {
                                IntSubstr = Intstr0.IndexOf(StrInt);
                                if (IntSubstr != -1)
                                {
                                    Bf = true;
                                }
                                else
                                {
                                    Bf = false;
                                }
                            }
                            else
                            {
                                for (var i = 0; i <= StrInt.Length - 1; i++)
                                {
                                    IntSign0 = StrInt.Substring(i, 1);
                                    IntSubstr = Intstr0.IndexOf(IntSign0);
                                    if (IntSubstr != -1)
                                    {
                                        db = db + 0;
                                    }
                                    else
                                    {
                                        db = i + 1;
                                        break;
                                    }
                                }

                                if (db == 0)
                                {
                                    Bf = true;
                                }
                                else
                                {
                                    Bf = false;
                                }
                            }
                        }
                        else
                        {
                            Bf = true;
                        }
                        //----小数部分－－－－
                        if (StrDecimal.Length > 0)
                        {
                            for (var j = 0; j <= StrDecimal.Length - 1; j++)
                            {
                                IntSign0 = StrDecimal.Substring(j, 1);
                                IntSubstr = Intstr0.IndexOf(IntSign0);
                                if (IntSubstr != -1)
                                {
                                    db = db + 0;
                                }
                                else
                                {
                                    db = j + 1;
                                    break;
                                }
                            }
                            if (db == 0)
                            {
                                Bl = true;
                            }
                            else
                            {
                                Bl = false;
                            }
                        }
                        else
                        {
                            Bl = false;
                        }
                        if ((Bf && Bl))
                        {
                            decimalbool = 0;
                        }
                        else
                        {
                            decimalbool = 1;
                        }
                    }
                }
                else
                {
                    decimalbool = 1;
                }
            }
            else
            {
                decimalbool = 1;
            }

            if (decimalbool == 0)
            {
                IsBool = true;
            }
            else
            {
                IsBool = false;
            }

            return IsBool;
        }

        #endregion

        #region "获取随机数"

        /// <summary>
        ///     获取随机数
        /// </summary>
        /// <param name="length">随机数长度</param>
        /// <returns></returns>
        public static string GetRandomPassword(int length)
        {
            var random = new byte[length/2];
            var rng = new RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(random);

            var sb = new StringBuilder(length);
            int i;
            for (i = 0; i < random.Length; i++)
            {
                sb.Append(string.Format("{0:X2}", random[i]));
            }
            return sb.ToString();
        }

        #endregion

        #region "获取用户IP地址"

        /// <summary>
        ///     获取用户IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {
            var user_IP = string.Empty;
            user_IP = HttpContext.Current.Request.UserHostAddress;
            return user_IP;
        }

        #endregion

        #region 字符串截取补字符函数

        /// <summary>
        ///     字符串截取补字符函数
        /// </summary>
        /// <param name="s">要处理的字符串</param>
        /// <param name="len">长度</param>
        /// <param name="b">补充的字符</param>
        /// <returns>处理后字符</returns>
        public static string splitStringLen(string s, int len, char b)
        {
            if (string.IsNullOrEmpty(s))
                return "";
            if (s.Length >= len)
                return s.Substring(0, len);
            return s.PadRight(len, b);
        }

        #endregion

        #region 脚本提示信息,并且跳转到最上层框架

        /// <summary>
        ///     脚本提示信息
        /// </summary>
        /// <param name="Msg">信息内容,可以为空,为空表示不出现提示窗口</param>
        /// <param name="Url">跳转地址</param>
        public static string Hint(string Msg, string Url)
        {
            var rStr = new StringBuilder();

            rStr.Append("<script language='javascript'>");
            if (Msg != "")
                rStr.Append("	alert('" + Msg + "');");

            if (Url != "")
                rStr.Append("	window.top.location.href = '" + Url + "';");

            rStr.Append("</script>");

            return rStr.ToString();
        }

        #endregion

        #region 脚本提示信息,并且跳转到当前框架内

        /// <summary>
        ///     脚本提示信息
        /// </summary>
        /// <param name="Msg">信息内容,可以为空,为空表示不出现提示窗口</param>
        /// <param name="Url">跳转地址,自已可以写入脚本</param>
        /// <returns></returns>
        public static string LocalHintJs(string Msg, string Url)
        {
            var rStr = new StringBuilder();

            rStr.Append("<script language='JavaScript'>\n");
            if (Msg != "")
                rStr.AppendFormat("	alert('{0}');\n", Msg);

            if (Url != "")
                rStr.Append(Url + "\n");
            rStr.Append("</script>");

            return rStr.ToString();
        }

        #endregion

        #region 脚本提示信息,并且跳转到当前框架内,地址为空时,返回上页

        /// <summary>
        ///     脚本提示信息
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string LocalHint(string Msg, string Url)
        {
            var rStr = new StringBuilder();

            rStr.Append("<script language='JavaScript'>\n");
            if (Msg != "")
                rStr.AppendFormat("	alert('{0}');\n", Msg);

            if (Url != "")
                rStr.AppendFormat("	window.location.href = '" + Url + "';\n");
            else
                rStr.AppendFormat(" window.history.back();");

            rStr.Append("</script>\n");

            return rStr.ToString();
        }

        #endregion

        #region "按当前日期和时间生成随机数"

        /// <summary>
        ///     按当前日期和时间生成随机数
        /// </summary>
        /// <param name="Num">附加随机数长度</param>
        /// <returns></returns>
        public static string sRndNum(int Num)
        {
            var sTmp_Str = DateTime.Today.Year + DateTime.Today.Month.ToString("00") + DateTime.Today.Day.ToString("00") + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00");
            return sTmp_Str + RndNum(Num);
        }

        #endregion

        #region 生成0-9随机数

        /// <summary>
        ///     生成0-9随机数
        /// </summary>
        /// <param name="VcodeNum">生成长度</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            var sb = new StringBuilder(VcodeNum);
            var rand = new Random();
            for (var i = 1; i < VcodeNum + 1; i++)
            {
                var t = rand.Next(9);
                sb.AppendFormat("{0}", t);
            }
            return sb.ToString();
        }

        #endregion

        #region "通过RNGCryptoServiceProvider 生成随机数 0-9"

        /// <summary>
        ///     通过RNGCryptoServiceProvider 生成随机数 0-9
        /// </summary>
        /// <param name="length">随机数长度</param>
        /// <returns></returns>
        public static string RndNumRNG(int length)
        {
            var bytes = new byte[16];
            var r = new RNGCryptoServiceProvider();
            var sb = new StringBuilder(length);
            for (var i = 0; i < length; i++)
            {
                r.GetBytes(bytes);
                sb.AppendFormat("{0}", (int) ((decimal) bytes[0]/256*10));
            }
            return sb.ToString();
        }

        #endregion

        #region "在当前路径上创建日期格式目录(20110620)"

        /// <summary>
        ///     在当前路径上创建日期格式目录(20110620)
        /// </summary>
        /// <param name="sPath">返回目录名</param>
        /// <returns></returns>
        public static string CreateDir(string sPath)
        {
            var sTemp = DateTime.Today.Year + DateTime.Today.Month.ToString("00") + DateTime.Today.Day.ToString("00");
            sPath += sTemp;
            var di = new DirectoryInfo(@sPath); //构造函数创建目录
            if (di.Exists == false)
            {
                di.Create();
            }

            return sTemp;
        }

        #endregion

        #region "检测是否为有效邮件地址格式"

        /// <summary>
        ///     检测是否为有效邮件地址格式
        /// </summary>
        /// <param name="strIn">输入邮件地址</param>
        /// <returns></returns>
        public static bool IsValidEmail(string strIn)
        {
            return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        #endregion

        #region 加密

        /// <summary>
        ///     以下代码等效于 PHP 的 SHA1() 代码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string SHA1(string data)
        {
            var temp1 = Encoding.UTF8.GetBytes(data);

            var sha = new SHA1CryptoServiceProvider();
            var temp2 = sha.ComputeHash(temp1);
            sha.Clear();

            // 注意， 不能用这个
            //string output = Convert.ToBase64String(temp2);

            var output = BitConverter.ToString(temp2);
            output = output.Replace("-", "");
            output = output.ToLower();
            return output;
        }

        #endregion

        /// <summary>
        ///     空字符串 返回0，否则不处理
        /// </summary>
        /// <param name="data">要判断的字符串</param>
        /// <returns></returns>
        public static string GetString(string data)
        {
            if (data == "")
            {
                return "0";
            }
            return data;
        }

        /// <summary>
        ///     空字符串返回0，否则返回经过double处理的结果。不处理异常
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static double GetDouble(string data)
        {
            if (data == "")
            {
                return 0;
            }
            return Convert.ToDouble(data);
        }

        #region 状态

        public static string GetStatus(string id)
        {
            if (id == "0")
            {
                return "未发送";
            }
            if (id == "1")
            {
                return "退回修改";
            }
            if (id == "2")
            {
                return "已发送";
            }
            if (id == "3")
            {
                return "审批完成";
            }
            return "未知状态";
        }

        #endregion

        #region 状态

        public static string GetShenChaDisplayStatus(string id)
        {
            if (id == "0")
            {
                return "审批中";
            }
            if (id == "1")
            {
                return "同意";
            }
            if (id == "2")
            {
                return "退回修改";
            }
            if (id == "3")
            {
                return "审批完成";
            }
            return "未知状态";
        }

        #endregion

        #region 获取用户真实姓名

        public static string GetRealName(string UserID)
        {
            return BLLFactory<T_UserInfoManager>.Instance.FindByID(UserID).RealName;
        }

        #endregion

        #region 获取用户角色名称

        public static string GetRoleName(string RoleID)
        {
            return BLLFactory<T_RoleManager>.Instance.FindByID(RoleID).RoleName;
        }

        #endregion

        #region "js信息提示框"

        /// <summary>
        ///     js信息提示框
        /// </summary>
        /// <param name="Message">提示信息文字</param>
        /// <param name="ReturnUrl">返回地址</param>
        /// <param name="rq"></param>
        public static void MessBox(string Message, string ReturnUrl, HttpContext rq)
        {
            var msgScript = new StringBuilder();
            msgScript.Append("<script language=JavaScript>\n");
            msgScript.Append("alert(\"" + Message + "\");\n");
            msgScript.Append("parent.location.href='" + ReturnUrl + "';\n");
            msgScript.Append("</script>\n");
            rq.Response.Write(msgScript.ToString());
            rq.Response.End();
        }

        /// <summary>
        ///     弹出Alert信息窗
        /// </summary>
        /// <param name="Message">信息内容</param>
        public static void MessBox(string Message)
        {
            var msgScript = new StringBuilder();
            msgScript.Append("<script language=JavaScript>\n");
            msgScript.Append("alert(\"" + Message + "\");\n");
            msgScript.Append("</script>\n");
            HttpContext.Current.Response.Write(msgScript.ToString());
        }

        #endregion

        #region 格式化字符串,符合SQL语句

        /// <summary>
        ///     格式化字符串,符合SQL语句
        /// </summary>
        /// <param name="formatStr">需要格式化的字符串</param>
        /// <returns>字符串</returns>
        public static string inSQL(string formatStr)
        {
            var rStr = formatStr;
            if (formatStr != null && formatStr != string.Empty)
            {
                rStr = rStr.Replace("'", "''");
                //rStr = rStr.Replace("\"", "\"\"");
            }
            return rStr;
        }

        /// <summary>
        ///     格式化字符串,是inSQL的反向
        /// </summary>
        /// <param name="formatStr"></param>
        /// <returns></returns>
        public static string outSQL(string formatStr)
        {
            var rStr = formatStr;
            if (rStr != null)
            {
                rStr = rStr.Replace("''", "'");
                rStr = rStr.Replace("\"\"", "\"");
            }
            return rStr;
        }

        /// <summary>
        ///     查询SQL语句,删除一些SQL注入问题
        /// </summary>
        /// <param name="formatStr">需要格式化的字符串</param>
        /// <returns></returns>
        public static string querySQL(string formatStr)
        {
            var rStr = formatStr;
            if (rStr != null && rStr != "")
            {
                rStr = rStr.Replace("'", "");
            }
            return rStr;
        }

        #endregion

        #region 日期处理

        /// <summary>
        ///     格式化日期为2006-12-22
        /// </summary>
        /// <param name="dTime"></param>
        /// <returns></returns>
        public static string formatDate(DateTime dTime)
        {
            string rStr;
            rStr = dTime.Year + "-" + dTime.Month + "-" + dTime.Day;
            return rStr;
        }


        /// <summary>
        ///     获取某年某月的总天数
        /// </summary>
        /// <param name="year">年</param>
        /// <param name="month">月</param>
        /// <returns>总天数</returns>
        public static int GetMonthDays(int year, int month)
        {
            if (month >= 1 && month <= 12)
            {
                int[] days1 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                int[] days2 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                if ((year%4 == 0 && year%100 != 0) || year%400 == 0)
                {
                    return days2[month - 1];
                }
                return days1[month - 1];
            }
            return 0;
        }

        #endregion
    }
}